package top.kikt.book.core.handlers

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.support.ui.WebDriverWait
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.getUrl
import top.kikt.book.util.metaContentWithProperty
import java.time.Duration

class Ddxs : BaseBookHandler() {
    override val host: String
        get() = "www.ddxs.com"

    override fun getUrlDocument(url: String): Document? {
        return chromiumGet(url) {
            while (true) {
                val element = it.findElements(By.tagName("table"))
                if (element != null && element.isNotEmpty()) {
                    break
                }
                Thread.sleep(100)
            }
        }
    }

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        println("document: $document")
        val title = document.metaContentWithProperty("og:novel:book_name")
        val author = document.metaContentWithProperty("og:novel:author")
        val cover = document.metaContentWithProperty("og:image")
        return BookMetaEntity(title, url, url, author, cover)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val table = document.getElementsByTag("table")[1]
        return table.getElementsByTag("a").mapIndexed { index, it ->
            val url = it.getUrl(menuUrl)
            val title = it.text()
            ChapterMetaEntity(title, index, url, it)
        }
    }

    private val driver: WebDriver by lazy {
        val driver = ChromeDriver(ChromeOptions())
        driver.get("https://www.ddxs.com/")
        driver
    }

    private fun chromiumGet(url: String): Document? {
        driver.navigate().to(url)
        WebDriverWait(driver, Duration.ofSeconds(1)).until {
            it.findElement(By.ById("contents"))
        }
        return Jsoup.parse(driver.pageSource)
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val url = chapterMetaEntity.url
        val doc = chromiumGet(url) ?: return null

        val content = doc.getElementById("contents")?.bookText() ?: return null
        return chapterMetaEntity.toChapterMetaEntity(content)
    }
}